<template>
  <div>
    <base-modal
      :title="$t('order.component.modifyOrderInfo')"
      :show.sync="visible"
      width="520px"
      :close-on-click-modal="false"
    >
      <div class="edit-dialog">
        <el-form
          ref="formRef"
          :model="orderForm"
          :rules="rules"
          
          label-position="top"
        >
          <!-- 未支付和已支付未发货的订单修改表单 -->
          <template v-if="orderState !== 3">
            <el-form-item :label="$t('order.component.consignee')" prop="name">
              <el-input
                v-model="orderForm.name"
                :placeholder="$t('order.placeHolder.enterConsignee')"
                style="width: 95%"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('common.base.contactNumber')" prop="contactsPhone">
              <el-input
                v-model="orderForm.contactsPhone"
                :placeholder="$t('im.chatMixin.tips2')"
                style="width: 95%"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('order.component.shipToAddress')" prop="address">
              <el-input
                v-model="orderForm.address"
                :placeholder="$t('order.placeHolder.enterShipToAddress')"
                style="width: 95%"
              ></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('order.component.orderAmount')"
              prop="payAmount"
              v-if="orderState === 1"
            >
              <el-input
                v-model="orderForm.payAmount"
                :placeholder="$t('order.placeHolder.enterOrderAmount')"
                style="width: 95%"
              ></el-input>
            </el-form-item>
          </template>

          <!-- 已发货的订单修改表单 -->
          <template v-else>
            <div class="form-area" v-if="isShow">
              <el-form-item :label="$t('common.form.preview.sparepart.colum16')">
                <el-select
                  v-model="orderForm.logisticsInfo"
                  :placeholder="$t('order.placeHolder.logisticsCompany')"
                  style="width: 95%"
                  clearable
                  @change="handleLogisticSelectChange"
                >
                  <el-option
                    v-for="(item, index) in orderInfo.logisticsList"
                    :key="`${item}_${index}`"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="form-area-title">{{$t('common.base.edit1')}}</div>
              <el-form-item :label="$t('common.base.logisticsNo')">
                <el-input
                  v-model="orderForm.logisticsNumber"
                  :placeholder="$t('common.validate.inputLogisticsNo')"
                  style="width: 95%"
                ></el-input>
              </el-form-item>
              <el-form-item
                :label="$t('common.base.logisticsCompany')"
                :prop="orderForm.logisticsNumber ? 'logisticsCompany' : ''"
              >
                <el-select
                  v-model="orderForm.logisticsCompany"
                  :placeholder="$t('order.placeHolder.logisticsCompany')"
                  style="width: 95%"
                >
                  <el-option
                    v-for="item in logisticsCompanyList"
                    :key="item.expressId"
                    :label="item.expressName"
                    :value="item.expressName"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>

            <div class="form-area">
              <el-form-item :label="$t('common.form.type.taskNo')">
                <el-select
                  v-model="orderForm.oldTaskNo"
                  :placeholder="$t('order.placeHolder.selectTaskNo')"
                  style="width: 95%"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in orderInfo.taskNoList"
                    :key="`${item}_${index}`"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="form-area-title">{{$t('common.base.edit1')}}</div>
              <el-form-item
                :label="$t('common.label.taskNo')"
                :prop="orderForm.oldTaskNo ? 'logisticsCompany' : ''"
              >
                <el-input
                  v-model="orderForm.newTaskNo"
                  :placeholder="$t('order.placeHolder.enterTaskNo')"
                  style="width: 95%"
                ></el-input>
              </el-form-item>
            </div>
          </template>

          <el-form-item :label="$t('order.component.orderRemarks')">
            <el-input
              type="textarea"
              :placeholder="$t('order.placeHolder.enterOrderRemarks')"
              v-model="orderForm.adminRemarks"
              style="width: 95%"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="handleDeliver" :loading="loading"
          >{{$t('common.base.save')}}</el-button
        >
      </div>
    </base-modal>
  </div>
</template>

<script>
import { queryOrderInfo, editOrderInfo } from '@src/api/PortalApi.ts';
import { getExpressConfig } from '@src/api/LinkcApi';
import { validatePhone } from '@src/util/validator'

export default {
  emits: ['reloadPage'],
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!validatePhone(value)) {
        callback(new Error(this.$t('order.placeHolder.phoneNumberLimit', {num1: '11'})));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      loading: false,
      orderForm: {
        name: '',
        contactsPhone: '',
        address: '',
        payAmount: 0,
        logisticsInfo: '',
        logisticsNumber: '',
        logisticsCompany: '',
        oldTaskNo: '',
        newTaskNo: '',
        adminRemarks: '',
      },
      rules: {
        name: [{ required: true, message: this.$t('order.placeHolder.enterConsignee'), trigger: 'blur' }],
        contactsPhone: [
          { required: true, message: this.$t('im.chatMixin.tips2'), trigger: 'blur' },
          {
            type: 'number',
            validator: checkPhone,
            message: this.$t('order.tips.correctNumberTip'),
            trigger: ['blur', 'change'],
          },
        ],
        address: [
          { required: true, message: this.$t('order.placeHolder.enterShipToAddress'), trigger: 'blur' },
        ],
        payAmount: [
          { required: true, message: this.$t('order.placeHolder.enterOrderAmount'), trigger: 'blur' },
        ],
        logisticsCompany: [
          { required: true, message: this.$t('order.placeHolder.logisticsCompany'), trigger: 'change' },
        ],
        logisticsNumber: [
          { required: true, message: this.$t('order.placeHolder.selectLogisticsNo'), trigger: 'blur' },
        ],
        newTaskNo: [
          { required: true, message: this.$t('order.placeHolder.enterTaskNo'), trigger: 'blur' },
        ],
      },
      logisticsCompanyList: [],
      logisticsSelectOptions: [],
      orderId: '',
      orderState: 0,
      isShow: true,
      orderInfo: {},
    };
  },
  emits: ['reloadPage'],
  methods: {
    open(id, state, isShow) {
      this.visible = true;
      this.orderId = id;
      this.orderState = state;
      this.isShow = isShow;

      this.orderForm = this.$options.data.call(this).orderForm;
      this.handleGetLogisticsCompany();
      this.getOrderInfo();
    },
    // 查询物流公司信息
    async handleGetLogisticsCompany() {
      try {
        const { code, data } = await getExpressConfig();

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('order.tips.obtainlogistics'));
        }

        this.logisticsCompanyList = data || [];
      } catch (error) {
        console.error('fetch logistics company list error', error);
      }
    },
    async getOrderInfo() {
      try {
        const { code, data } = await queryOrderInfo({ orderId: this.orderId });

        if (code !== '200' || !data) {
          this.loading = false;
          return this.$message.error(this.$t('order.tips.queryOrderFailed'));
        }

        this.orderInfo = data;
        this.orderForm.name = data?.name || '';
        this.orderForm.contactsPhone = data?.contactsPhone || '';
        this.orderForm.address = data?.address || '';
        this.orderForm.payAmount = data?.payAmount || 0;
        this.orderForm.adminRemarks = data?.adminRemarks || '';

        this.orderInfo.logisticsList =
          data?.logisticsVOList?.map(
            item => `${item.logisticsCompany} ${item.logisticsNumber}`
          ) || [];
        // this.orderForm.logisticsInfo = this.orderInfo.logisticsList?.[0] || '';
        // this.handleLogisticSelectChange(this.orderForm.logisticsInfo);
      } catch (error) {
        console.error('fetch order info error', error);
      }
    },
    handleLogisticSelectChange(val) {
      this.orderForm.logisticsInfo = val;

      const arr = val.split(' ');
      this.orderForm.logisticsCompany = arr[0];
      this.orderForm.logisticsNumber = arr[1];
    },
    buildParams() {
      const params = {
        name: this.orderForm.name,
        contactsPhone: this.orderForm.contactsPhone,
        address: this.orderForm.address,
        payAmount: this.orderForm.payAmount,
        orderId: this.orderId,
      };

      if (this.orderForm.adminRemarks) {
        params.adminRemarks = this.orderForm.adminRemarks;
      }

      if (this.orderForm.logisticsNumber) {
        const arr = this.orderForm.logisticsInfo
          ? this.orderForm.logisticsInfo.split(' ')
          : null;
        params.newLogisticsRequest = {
          logisticsCompany: this.orderForm.logisticsCompany,
          logisticsNumber: this.orderForm.logisticsNumber,
        };
        params.oldLogisticsRequest = {
          logisticsCompany: arr ? arr[0] : '',
          logisticsNumber: arr ? arr[1] : '',
        };
      }

      if (this.orderForm.newTaskNo) {
        params.newTaskNo = this.orderForm.newTaskNo;
        params.oldTaskNo = this.orderForm.oldTaskNo;
      }

      return params;
    },
    handleDeliver() {
      if (
        this.orderState === 3 &&
        !this.orderForm.logisticsInfo &&
        !this.orderForm.oldTaskNo &&
        !this.orderForm.adminRemarks
      ) {
        return this.$message.warning(this.$t('order.tips.selectModifyInfo'));
      }

      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.handleUpdate();
        }
      });
    },
    async handleUpdate() {
      try {
        this.loading = true;
        const params = this.buildParams();
        const { code, msg } = await editOrderInfo(params);

        if (code !== '200') {
          this.loading = false;
          return this.$message.error(msg || this.$t('order.tips.changeOrderFailed'));
        }

        this.$message.success(this.$t('order.tips.changeOrderSuccess'));
        this.visible = false;
        this.loading = false;
        this.orderForm = this.$options.data.call(this).orderForm;

        setTimeout(() => {
          this.$emit('reloadPage');
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('update order error', error);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.edit-dialog {
  padding: 30px;
}

.form-area {
  background: #fafafa;
  padding: 16px 0;
  margin-bottom: 16px;

  &-title {
    color: #8c8c8c;
    margin: 0 0 10px 12px;
    font-size: 14px;
  }
}
</style>
